const EOF = Symbol("EOF")
class Parser {
  constructor() {
    this.state = start
    this.httpVersion = ''
    this.httpCode = ''
    this.httpText = ''
    this.key = ''
    this.value = ''
    this.kv = {

    }
  }
  write(data) {
    console.log(data)
    for (let c of data) {
      console.log({ 'fn': this.state })
      this.state = this.state(c)
    }
  }
  recevieHttpVersion(c) {
    this.httpVersion += c
  }

  recevieHttpCode(c) {
    this.httpCode += c
  }
  recevieHttpText(c) {
    this.httpText += c
  }
  recevieKey(c) {
    this.key += c
  }
  recevieValue(c) {
    this.value += c
  }
  setKV() {
    this.kv[this.key] = this.value
    this.key = ''
    this.value = ''
  }
  end() {
    console.log({
      headers: this.kv
    })
    console.log(this.httpCode)
    this.state = this.state(EOF)
  }
}

function start(c) {
  console.log({ start: c })
  if (c == ' ') {
    return foundCode
  } else {
    this.recevieHttpVersion(c)
    return start
  }
}


function foundCode(c) {
  console.log({ foundCode: c })
  if (c == ' ') {
    return foundText
  } else {
    this.recevieHttpCode(c)
    return foundCode
  }
}

function foundText(c) {
  console.log({ foundText: c })
  if (c == '\r') {
    return gotKey
  } else {
    this.recevieHttpText(c)
    return foundText
  }
}

function gotKey(c) {
  if (c === EOF) {
    return end
  }
  else if (c == '\n') {
    return gotKey
  } else if (c == ":") {
    return gotValue
  } else {
    console.log({ 'fn': c })
    this.recevieKey(c)
    return gotKey
  }
}

function gotValue(c) {
  console.log({ c })
  if (c == '\r') {
    this.setKV()
    return gotKey
  } else if (c == '\n') {
    return gotKey
  } else {
    this.recevieValue(c)
    return gotValue
  }
}


function end(c) {
  return end
}


module.exports = Parser

